package com.jiefutong.zyt.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.jiefutong.zyt.R;
import com.jiefutong.zyt.WebActivity;
import com.jiefutong.zyt.WebViewActivity;
import com.jiefutong.zyt.apiservice.ApiService;
import com.jiefutong.zyt.bean.MineVO;
import com.jiefutong.zyt.bean.UserInfoVO;
import com.jiefutong.zyt.http.XCRRestProvider;
import com.jiefutong.zyt.utils.CircleTransform;
import com.jiefutong.zyt.utils.RoundTransform;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by a2384760 on 2019/3/19.
 */

public class MineFragment  extends Fragment implements View.OnClickListener{
    View view;
    //头像
    private ImageView headerIV;
    private TextView accountTV;
    private TextView codeTV;
    //我的金币
    private LinearLayout balanceLL;
    private TextView balanceTV;
    //金豆
    private LinearLayout packetLL;
    private TextView packetTV;
    //银豆
    private LinearLayout profitLL;
    private TextView profitTV;
    //钱包
    private LinearLayout walletLL;
    //待付款
    private LinearLayout waitPayLL;
    //代发货
    private LinearLayout waitSendLL;
    //待收货
    private LinearLayout waitReceiveLL;
    //退换货
    private LinearLayout backGoodsLL;
    //我的订单
    private LinearLayout myOrderLL;
    //掌易通订单
    private LinearLayout orderLL;
    //邀请好友
    private LinearLayout inviteLL;
    private GridView gridViewGV;

    private GridView recommendGV;
    //领取红包
    private ImageView receiveRedIV;
    private ScrollView scrollView;

    private TextView titleTV;
    int mAlpha = 0;

    ApiService apiService= XCRRestProvider.getInstance().create(ApiService.class);
    List<MineVO.DataBean.ToolsBean> toolDatas=new ArrayList<>();

    List<MineVO.DataBean.RecommendsBean> goodsDatas=new ArrayList<>();
    private boolean isViewPrepared=false;//是否初始化完成

    private ImageView setIV;
    private LinearLayout userInfoLL;

    private LinearLayout titleLL;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_mine,null);
        initView();
        loadInfo();
        loadDatas();

        gridViewGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MineVO.DataBean.ToolsBean toolsBean=toolDatas.get(position);
                Intent intent=new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url",toolsBean.getUri());
                intent.putExtra("title",toolsBean.getTitle());
                startActivity(intent);
            }
        });

        recommendGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MineVO.DataBean.RecommendsBean goodsBean=goodsDatas.get(position);
                Intent intent=new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url",goodsBean.getUri());
                intent.putExtra("title","商品详情");
                startActivity(intent);
            }
        });



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    /**  ScrollView 滚动动态改变标题栏 */
                    // 滑动的最小距离（自行定义，you happy jiu ok）
                    int minHeight = 50;
                    // 滑动的最大距离（自行定义，you happy jiu ok）
                    int maxHeight = 120;

                    // 滑动距离小于定义得最小距离
                    if (scrollView.getScrollY() <= minHeight) {
                        mAlpha = 0;
                    }
                    // 滑动距离大于定义得最大距离
                    else if (scrollView.getScrollY() > maxHeight) {
                        mAlpha = 255;
                    }
                    // 滑动距离处于最小和最大距离之间
                    else {
                        // （滑动距离 - 开始变化距离）：最大限制距离 = mAlpha ：255
                        mAlpha = (scrollView.getScrollY() - minHeight) * 255 / (maxHeight - minHeight);
                    }

                    // 初始状态 标题栏/导航栏透明等
                    if (mAlpha <= 10) {
                        setViewBackgroundAlpha(titleLL, 0);
                        titleTV.setTextColor(Color.argb(255, 255, 255, 255));

                    }
                    //  终止状态：标题栏/导航栏 不在进行变化
                    else if (mAlpha >= 255) {
                        setViewBackgroundAlpha(titleLL, 255);
                        titleTV.setTextColor(Color.argb(255, 51, 51, 51));
                        //iconColorFilter(Color.parseColor("#000000"));

                    }
                    // 变化中状态：标题栏/导航栏随ScrollView 的滑动而产生相应变化
                    else {
                        setViewBackgroundAlpha(titleLL, mAlpha);
                        titleTV.setTextColor(Color.argb(255, 255 - mAlpha, 255 - mAlpha, 255 - mAlpha));
                    }

                }
            });
        }
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        // 判断该Fragment时候已经正在前台显示，就可以知道什么时候去加载数据了
       /* if (isVisibleToUser && isViewPrepared) {
            loadInfo();
            loadDatas();
        }*/
        super.setUserVisibleHint(isVisibleToUser);
    }
    /**
     * 初始化导航栏
     * 包括：
     * 导航栏背景透明度，
     * 操作按钮颜色透明度，
     * 标题文字颜色等。
     */
    private void initNavigationBar() {
        setViewBackgroundAlpha(titleLL, 0);

        //iconColorFilter(Color.parseColor("#ffffff"));
    }


    /**
     * 设置View的背景透明度
     *
     * @param view
     * @param alpha
     */
    public void setViewBackgroundAlpha(View view, int alpha) {
        if (view == null) return;

        Drawable drawable = view.getBackground();
        System.out.println("---------back:"+drawable.getAlpha());
        if (drawable != null) {
            drawable.setAlpha(alpha);
        }
    }

    private void loadDatas() {
        Call<MineVO> call=apiService.getMineFragment();
        call.enqueue(new Callback<MineVO>() {
            @Override
            public void onResponse(Call<MineVO> call, Response<MineVO> response) {
                if(response.isSuccessful()){
                    MineVO mineVO=response.body();
                    if(mineVO.getStatus().equals("success")){
                        MineVO.DataBean data=mineVO.getData();
                        toolDatas=data.getTools();
                        goodsDatas=data.getRecommends();




                        ToolAdapter adapter=new ToolAdapter();
                        gridViewGV.setAdapter(adapter);
                        setListViewHeightBasedOnChildren(gridViewGV);


                        RecommedAdapter recommedAdapter=new RecommedAdapter();
                        recommendGV.setAdapter(recommedAdapter);
                        setListViewHeightBasedOnChildren(recommendGV);
                    }
                }

            }

            @Override
            public void onFailure(Call<MineVO> call, Throwable t) {

            }
        });


    }

    private void loadInfo() {
        Call<UserInfoVO> call=apiService.getUserInfo();
        call.enqueue(new Callback<UserInfoVO>() {
            @Override
            public void onResponse(Call<UserInfoVO> call, Response<UserInfoVO> response) {
                if(response.isSuccessful()){
                    UserInfoVO infoVO=response.body();
                    if(infoVO.getStatus().equals("success")){
                        UserInfoVO.DataBean data=infoVO.getData();
                        if (!TextUtils.isEmpty(data.getAvatar())) {
                            Picasso.with(getContext()).load(data.getAvatar()).transform(new CircleTransform()).into(headerIV);
                        }else {
                            headerIV.setImageResource(R.mipmap.jft_but_defaulthead);
                        }
                        accountTV.setText(data.getUser_name());
                        codeTV.setText("邀请码："+data.getInvite_code());
                        balanceTV.setText(data.getCredit3());
                        packetTV.setText(data.getCredit2());
                        profitTV.setText(data.getCredit1());

                    }else{
                        Toast.makeText(getContext(),infoVO.getMessage(),Toast.LENGTH_SHORT).show();
                    }




                }
            }

            @Override
            public void onFailure(Call<UserInfoVO> call, Throwable t) {
                Toast.makeText(getContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initView() {
        titleTV=view.findViewById(R.id.fragmentMine_titleTV);
        titleLL=view.findViewById(R.id.fragmentMine_titleLL);
        initNavigationBar();
        //头像
        headerIV=view.findViewById(R.id.fragmentMine_headerIV);
        accountTV=view.findViewById(R.id.fragmentMine_accountTV);
        codeTV=view.findViewById(R.id.fragmentMine_codeTV);
        //我的金币
        balanceLL=view.findViewById(R.id.fragmentMine_balanceLL);
        balanceLL.setOnClickListener(this);
        balanceTV=view.findViewById(R.id.fragmentMine_balanceTV);
        //金豆
        packetLL=view.findViewById(R.id.fragmentMine_packetLL);
        packetLL.setOnClickListener(this);
        packetTV=view.findViewById(R.id.fragmentMine_packetTV);
        //银豆
       profitLL=view.findViewById(R.id.fragmentMine_profitLL);
        profitLL.setOnClickListener(this);
        profitTV=view.findViewById(R.id.fragmentMine_profitTV);
        //钱包
        walletLL=view.findViewById(R.id.fragmentMine_walletLL);
        walletLL.setOnClickListener(this);
        //待付款
        waitPayLL=view.findViewById(R.id.fragmentMine_waitPayLL);
        waitPayLL.setOnClickListener(this);
        //代发货
        waitSendLL=view.findViewById(R.id.fragmentMine_waitSendLL);
        waitSendLL.setOnClickListener(this);
        //待收货
       waitReceiveLL=view.findViewById(R.id.fragmentMine_waitReceiveLL);
        waitReceiveLL.setOnClickListener(this);
        //退换货
        backGoodsLL=view.findViewById(R.id.fragmentMine_backGoodsLL);
        backGoodsLL.setOnClickListener(this);
        //我的订单
         myOrderLL=view.findViewById(R.id.fragmentMine_myOrderLL);
        myOrderLL.setOnClickListener(this);
        //掌易通订单
       orderLL=view.findViewById(R.id.fragmentMine_orderLL);
        orderLL.setOnClickListener(this);
        //邀请好友
         inviteLL=view.findViewById(R.id.fragmentMine_inviteLL);
        inviteLL.setOnClickListener(this);
        gridViewGV=view.findViewById(R.id.fragmentMine_gridviewGV);
        recommendGV=view.findViewById(R.id.fragmentMine_recommendGV);
        //领取红包
        receiveRedIV=view.findViewById(R.id.fragmentMine_receiveRedIV);
        receiveRedIV.setOnClickListener(this);
        scrollView=view.findViewById(R.id.fragmentMine_scrollView);
        setIV=view.findViewById(R.id.fragmentMain_setIV);
        setIV.setOnClickListener(this);
        userInfoLL=view.findViewById(R.id.fragmentMain_userInfoLL);
        userInfoLL.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fragmentMine_profitLL:
                //我的银豆
                Intent intent3=new Intent(getActivity(),WebViewActivity.class);
                intent3.putExtra("url","https://zyt.jiefutong.net/ElectronicAssets");
                intent3.putExtra("title","我的银豆");
                getActivity().startActivity(intent3);
                break;
            case R.id.fragmentMine_balanceLL:
                //我的金币
                Intent intent2=new Intent(getActivity(),WebViewActivity.class);
                intent2.putExtra("url","https://zyt.jiefutong.net/ElectronicIntegral");
                intent2.putExtra("title","我的金币");
                getActivity().startActivity(intent2);
                break;
            case R.id.fragmentMine_packetLL:
                //我的金豆
                Intent intent=new Intent(getActivity(),WebViewActivity.class);
                intent.putExtra("url","https://zyt.jiefutong.net/ConsumerCoupons");
                intent.putExtra("title","我的金豆");
                getActivity().startActivity(intent);
                break;
            case R.id.fragmentMine_walletLL:
                //钱包
                break;
            case R.id.fragmentMine_waitPayLL:
                //待付款
                Intent intent8=new Intent(getActivity(),WebViewActivity.class);
                intent8.putExtra("url","https://zyt.jiefutong.net/mall/jiefutong/order.html?i=1&status=0");
                intent8.putExtra("title","待付款");
                getActivity().startActivity(intent8);

                break;
            case R.id.fragmentMine_waitSendLL:
                //待发货
                Intent intent9=new Intent(getActivity(),WebViewActivity.class);
                intent9.putExtra("url","https://zyt.jiefutong.net/mall/jiefutong/order.html?i=1&status=1");
                intent9.putExtra("title","待发货");
                getActivity().startActivity(intent9);
                break;
            case R.id.fragmentMine_waitReceiveLL:
               //待收货
                Intent intent10=new Intent(getActivity(),WebViewActivity.class);
                intent10.putExtra("url","https://zyt.jiefutong.net/mall/jiefutong/order.html?i=1&status=2");
                intent10.putExtra("title","待收货");
                getActivity().startActivity(intent10);
                break;
            case R.id.fragmentMine_backGoodsLL:
                //退换货
                Intent intent11=new Intent(getActivity(),WebViewActivity.class);
                intent11.putExtra("url","https://zyt.jiefutong.net/mall/jiefutong/order.html?i=1&status=3");
                intent11.putExtra("title","退换货");
                getActivity().startActivity(intent11);
                break;
            case R.id.fragmentMine_myOrderLL:
                //我的订单
                Intent intent12=new Intent(getActivity(),WebViewActivity.class);
                intent12.putExtra("url","https://zyt.jiefutong.net/mall/jiefutong/order.html?i=1");
                intent12.putExtra("title","我的订单");
                getActivity().startActivity(intent12);
                break;
            case R.id.fragmentMine_orderLL:
                //掌益通订单
                break;
            case R.id.fragmentMine_inviteLL:
                //邀请好友
                Intent intent4=new Intent(getActivity(),WebViewActivity.class);
                intent4.putExtra("url","https://zyt.jiefutong.net/InvitationReturn");
                intent4.putExtra("title","邀请好友");
                getActivity().startActivity(intent4);
                break;

            case R.id.fragmentMine_receiveRedIV:
                //领取红包
                Intent intent5=new Intent(getActivity(),WebViewActivity.class);
                intent5.putExtra("url","https://zyt.jiefutong.net/DailyRedPacket");
                intent5.putExtra("title","每日红包");
                getActivity().startActivity(intent5);
                break;
            case R.id.fragmentMain_setIV:
                Intent intent6=new Intent(getActivity(),WebViewActivity.class);
                intent6.putExtra("url","https://zyt.jiefutong.net/Setting");
                intent6.putExtra("title","设置页面");
                getActivity().startActivity(intent6);
                break;
            case R.id.fragmentMain_userInfoLL:
                Intent intent7=new Intent(getActivity(),WebViewActivity.class);
                intent7.putExtra("url","https://zyt.jiefutong.net/PersonalData");
                intent7.putExtra("title","个人资料");
                getActivity().startActivity(intent7);


        }

    }


    public class RecommedAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return goodsDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return goodsDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public class ViewHolder{
            private ImageView imgIV;
            private TextView titleTV;
            private TextView priceTV;
            private TextView buyTV;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder=null;
            if(convertView==null){
                convertView=View.inflate(getActivity(),R.layout.item_mine_recommend,null);
                viewHolder=new ViewHolder();
                convertView.setTag(viewHolder);
            }else{
                viewHolder= (ViewHolder) convertView.getTag();
            }
            final MineVO.DataBean.RecommendsBean data=goodsDatas.get(position);
            viewHolder.imgIV=convertView.findViewById(R.id.itemRecommend_imgIV);
            viewHolder.titleTV=convertView.findViewById(R.id.itemRecommend_titleTV);
            viewHolder.priceTV=convertView.findViewById(R.id.itemRecommend_priceTV);
            viewHolder.buyTV=convertView.findViewById(R.id.itemRecommend_buyTV);
            if (!TextUtils.isEmpty(data.getPic())) {
                Picasso.with(getContext()).load(data.getPic()).into(viewHolder.imgIV);
            }
            viewHolder.titleTV.setText(data.getTitle());
            viewHolder.priceTV.setText("￥"+data.getMinprice());

            return convertView;
        }
    }

    public class ToolAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return toolDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return toolDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public class ViewHolder{
            private ImageView imgIV;
            private TextView textTV;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder=null;
            if(convertView==null){
                convertView=View.inflate(getActivity(),R.layout.item_mine,null);
                viewHolder=new ViewHolder();
                convertView.setTag(viewHolder);
            }else{
                viewHolder= (ViewHolder) convertView.getTag();
            }
            final MineVO.DataBean.ToolsBean data=toolDatas.get(position);
            viewHolder.imgIV=convertView.findViewById(R.id.itemMine_imgIV);
            viewHolder.textTV=convertView.findViewById(R.id.itemMine_textTV);
            if (!TextUtils.isEmpty(data.getIcon())) {
                Picasso.with(getContext()).load(data.getIcon()).transform(new RoundTransform(10)).into(viewHolder.imgIV);
            }
            viewHolder.textTV.setText(data.getTitle());
            return convertView;
        }
    }

    /**
     * 动态设置ListView的高度
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 4;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
      /*  // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);*/
        // 设置参数
        listView.setLayoutParams(params);
    }
}
